/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ConsultoresDialog.java
 *
 * Created on Oct 22, 2010, 11:06:21 AM
 */
package br.com.tbp.gui;

import br.com.tbp.controle.ControleConsultor;
import br.com.tbp.controle.ControlePedido;
import br.com.tbp.exception.PersistenciaException;
import br.com.tbp.gui.table.ConsultoresTableModel;
import br.com.tbp.gui.table.DefaultTableRenderer;
import br.com.tbp.gui.table.JTableUtils;
import br.com.tbp.model.domain.Consultor;
import br.com.tbp.model.domain.Foto;
import com.towel.swing.table.TableFilter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;

/**
 *
 * @author Diego Freire
 */
public class ConsultoresDialog extends javax.swing.JDialog {

    private Consultor consultor = null;
    private boolean select = false;
    private ConsultoresTableModel model;
    private DefaultTableCellRenderer renderer = new DefaultTableRenderer();
    private ControleConsultor controle = new ControleConsultor();
    private MenuPrincipal menu;
    private  TableFilter filter;

    public ConsultoresDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        if (parent instanceof MenuPrincipal) {
            this.menu = (MenuPrincipal) parent;
        }
        setLocationRelativeTo(null);
    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        contentPanel = new javax.swing.JPanel();
        split1 = new javax.swing.JSplitPane();
        buscaPanel = new javax.swing.JPanel();
        radio1 = new javax.swing.JRadioButton();
        radio2 = new javax.swing.JRadioButton();
        jLabel1 = new javax.swing.JLabel();
        inputTextField = new javax.swing.JFormattedTextField();
        okButton = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jPanel6 = new javax.swing.JPanel();
        scrollpane = new javax.swing.JScrollPane();
        tabela = new javax.swing.JTable();
        jPanel7 = new javax.swing.JPanel();
        removerButton = new javax.swing.JButton();
        selecionarServicoButton = new javax.swing.JButton();
        fecharButton = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        listarButton = new javax.swing.JButton();
        cadastrarButton = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        msgLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("TBP - Consultores");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        contentPanel.setLayout(new java.awt.BorderLayout());

        buttonGroup1.add(radio1);
        radio1.setSelected(true);
        radio1.setText("Nome do consultor");
        radio1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radio1ActionPerformed(evt);
            }
        });

        buttonGroup1.add(radio2);
        radio2.setText("ID consultor");
        radio2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radio2ActionPerformed(evt);
            }
        });

        jLabel1.setText("Busca simples");

        inputTextField.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 5, 1, 1));
        inputTextField.setToolTipText("Selecione o filtro abaixo e digite para buscar");
        inputTextField.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        inputTextField.setFont(new java.awt.Font("Dialog", 0, 15));
        inputTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inputTextFieldActionPerformed(evt);
            }
        });

        okButton.setText("OK");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });

        jLabel2.setText("> Selecione o filtro abaixo e digite para buscar");

        javax.swing.GroupLayout buscaPanelLayout = new javax.swing.GroupLayout(buscaPanel);
        buscaPanel.setLayout(buscaPanelLayout);
        buscaPanelLayout.setHorizontalGroup(
            buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buscaPanelLayout.createSequentialGroup()
                .addGroup(buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(buscaPanelLayout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(radio2)
                            .addComponent(radio1, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)))
                    .addGroup(buscaPanelLayout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(buscaPanelLayout.createSequentialGroup()
                                .addComponent(inputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(okButton))
                            .addComponent(jLabel2))))
                .addContainerGap())
        );
        buscaPanelLayout.setVerticalGroup(
            buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(buscaPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(buscaPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(inputTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radio1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(radio2)
                .addContainerGap(194, Short.MAX_VALUE))
        );

        split1.setLeftComponent(buscaPanel);

        jPanel6.setLayout(new java.awt.BorderLayout());

        scrollpane.setPreferredSize(new java.awt.Dimension(700, 350));

        tabela.setFont(new java.awt.Font("Dialog", 0, 13)); // NOI18N
        tabela.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tabela.setRowHeight(22);
        tabela.setRowSelectionAllowed(false);
        tabela.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tabela.setShowHorizontalLines(false);
        tabela.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabelaMouseClicked(evt);
            }
        });
        scrollpane.setViewportView(tabela);

        jPanel6.add(scrollpane, java.awt.BorderLayout.CENTER);

        jPanel7.setBackground(new java.awt.Color(255, 255, 255));
        jPanel7.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        removerButton.setBackground(new java.awt.Color(150, 184, 250));
        removerButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/trash.png"))); // NOI18N
        removerButton.setText("Remover Consultor");
        removerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removerButtonActionPerformed(evt);
            }
        });
        jPanel7.add(removerButton);

        selecionarServicoButton.setBackground(new java.awt.Color(150, 184, 250));
        selecionarServicoButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/cursor16.png"))); // NOI18N
        selecionarServicoButton.setText("Selecionar Consultor");
        selecionarServicoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selecionarServicoButtonActionPerformed(evt);
            }
        });
        jPanel7.add(selecionarServicoButton);

        fecharButton.setBackground(new java.awt.Color(150, 184, 250));
        fecharButton.setText("Fechar (ESC)");
        fecharButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fecharButtonActionPerformed(evt);
            }
        });
        jPanel7.add(fecharButton);

        jPanel6.add(jPanel7, java.awt.BorderLayout.PAGE_END);

        jPanel3.setBackground(new java.awt.Color(255, 255, 255));
        jPanel3.setLayout(new java.awt.BorderLayout());

        jPanel4.setBackground(new java.awt.Color(255, 255, 255));

        listarButton.setBackground(new java.awt.Color(150, 184, 250));
        listarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/listar16.png"))); // NOI18N
        listarButton.setText("Listar Todos");
        listarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                listarButtonActionPerformed(evt);
            }
        });
        jPanel4.add(listarButton);

        cadastrarButton.setBackground(new java.awt.Color(150, 184, 250));
        cadastrarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/consultor16.png"))); // NOI18N
        cadastrarButton.setText("Novo Consultor");
        cadastrarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cadastrarButtonActionPerformed(evt);
            }
        });
        jPanel4.add(cadastrarButton);

        jPanel3.add(jPanel4, java.awt.BorderLayout.LINE_END);

        jPanel5.setBackground(new java.awt.Color(255, 255, 255));
        jPanel5.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 4, 1, 1));
        jPanel5.setLayout(new java.awt.BorderLayout());

        msgLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/tbp/resources/consultor.png"))); // NOI18N
        msgLabel.setText("mensagem");
        msgLabel.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jPanel5.add(msgLabel, java.awt.BorderLayout.PAGE_END);

        jPanel3.add(jPanel5, java.awt.BorderLayout.LINE_START);

        jPanel6.add(jPanel3, java.awt.BorderLayout.PAGE_START);

        split1.setRightComponent(jPanel6);

        contentPanel.add(split1, java.awt.BorderLayout.CENTER);

        getContentPane().add(contentPanel, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tabelaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelaMouseClicked
        if (evt.getClickCount() == 2) {
            selecionarConsultor(tabela.getSelectedRow());
        }
}//GEN-LAST:event_tabelaMouseClicked

    private void selecionarServicoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selecionarServicoButtonActionPerformed
        selecionarConsultor(tabela.getSelectedRow());
}//GEN-LAST:event_selecionarServicoButtonActionPerformed

    private void fecharButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fecharButtonActionPerformed
        dispose();
    }//GEN-LAST:event_fecharButtonActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        try {
            this.refreshUltimosCadastrados(controle.pesquisar(0, 30));
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
    }//GEN-LAST:event_formWindowOpened

    private void radio1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radio1ActionPerformed
        inputTextField.requestFocus();
        inputTextField.selectAll();
    }//GEN-LAST:event_radio1ActionPerformed

    private void radio2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radio2ActionPerformed
        inputTextField.requestFocus();
        inputTextField.selectAll();
    }//GEN-LAST:event_radio2ActionPerformed

    private void cadastrarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cadastrarButtonActionPerformed
        ConsultorDialog dialog = new ConsultorDialog(this.menu, "TBP - Consultor", true);
        dialog.setConsultor(new Consultor());
        dialog.setNovoConsultor(true);
        dialog.setVisible(true);
        if (dialog.refresh()) {
            try {
                refresh(controle.pesquisar());
            } catch (PersistenciaException pex) {
                System.out.println(pex.getMessage());
            }
        }
    }//GEN-LAST:event_cadastrarButtonActionPerformed

    private void listarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_listarButtonActionPerformed
        try {
            this.refresh(controle.pesquisar());
        } catch (PersistenciaException pex) {
            System.out.println(pex.getMessage());
        }
}//GEN-LAST:event_listarButtonActionPerformed

    private void removerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removerButtonActionPerformed
        int row = tabela.getSelectedRow();
        if (row >= 0) {
            Consultor c = model.getConsultor(row);
            if (c != null) {
                Object[] opcoes = {"Sim", "Não"};
                int resposta = JOptionPane.showOptionDialog(this,
                        "Confirma remover o consultor " + c.getNome() + " ?",
                        "Atenção", JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
                        null, opcoes, opcoes[1]);
                if (resposta == 0) {
                    try {
                        controle.remover(c);

                        ControlePedido controle_pedido = new ControlePedido();
                        controle_pedido.removerPedidoPeloConsultor(c);

                        model.removeConsultor(c);
                        JOptionPane.showMessageDialog(null, "O consultor " + c.getNome() + " foi removido com sucesso.",
                                "Informação", JOptionPane.INFORMATION_MESSAGE);
                    } catch (PersistenciaException pex) {
                        System.out.println(pex.getMessage());
                    }
                }
            }
        }
    }//GEN-LAST:event_removerButtonActionPerformed

    private void inputTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_inputTextFieldActionPerformed
        buscaConsultor(inputTextField.getText());
}//GEN-LAST:event_inputTextFieldActionPerformed

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        buscaConsultor(inputTextField.getText());
}//GEN-LAST:event_okButtonActionPerformed

    public static void main(String args[]) {
        UIManager.put("swing.boldMetal", Boolean.FALSE);
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ConsultoresDialog dialog = new ConsultoresDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    private void refresh(Consultor c) {
        List<Consultor> lista = new ArrayList<Consultor>();
        if(c != null) {
            lista.add(c);
        }
        refresh(lista);
    }

    private void refreshUltimosCadastrados(List<Consultor> lista) {
        model = new ConsultoresTableModel(lista);
        tabela.setModel(model);
        filter = new TableFilter(tabela);
        if (lista.isEmpty()) {
            msgLabel.setText("Não há nenhum consultor cadastrado");
        } else if (lista.size() == 1) {
            msgLabel.setText("Último consultor cadastrado");
        } else {
            msgLabel.setText("Últimos " + lista.size() + " consultores cadastrados");
        }
        JTableUtils.fitAllColumns(tabela, renderer);
        inputTextField.requestFocus();
        inputTextField.selectAll();
    }

    private void refresh(List<Consultor> lista) {
        model = new ConsultoresTableModel(lista);
        tabela.setModel(model);
        filter = new TableFilter(tabela);
        if (lista.isEmpty()) {
            msgLabel.setText("Não há nenhum consultor cadastrado");
        } else if (lista.size() == 1) {
            msgLabel.setText("Exibindo 1 consultor cadastrado");
        } else {
            msgLabel.setText("Exibindo " + lista.size() + " consultores cadastrados");
        }
        JTableUtils.fitAllColumns(tabela, renderer);
        inputTextField.requestFocus();
        inputTextField.selectAll();
    }
    // <editor-fold defaultstate="collapsed" desc="Declaration of class members">
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel buscaPanel;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton cadastrarButton;
    private javax.swing.JPanel contentPanel;
    private javax.swing.JButton fecharButton;
    private javax.swing.JFormattedTextField inputTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JButton listarButton;
    private javax.swing.JLabel msgLabel;
    private javax.swing.JButton okButton;
    private javax.swing.JRadioButton radio1;
    private javax.swing.JRadioButton radio2;
    private javax.swing.JButton removerButton;
    private javax.swing.JScrollPane scrollpane;
    private javax.swing.JButton selecionarServicoButton;
    private javax.swing.JSplitPane split1;
    private javax.swing.JTable tabela;
    // End of variables declaration//GEN-END:variables

    // </editor-fold>
    public ConsultoresTableModel getModel() {
        return model;
    }

    @Override
    protected JRootPane createRootPane() {
        ActionListener closeListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                fecharButtonActionPerformed(e);
            }
        };
        KeyStroke stroke =
                KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
        JRootPane myRootPane = new JRootPane();
        myRootPane.registerKeyboardAction(
                closeListener, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW);

        return myRootPane;
    }

    public Consultor getConsultor() {
        return consultor;
    }

    public void setConsultor(Consultor consultor) {
        this.consultor = consultor;
    }

    public boolean isSelect() {
        return select;
    }

    public void setSelect(boolean select) {
        this.select = select;
    }

    private void selecionarConsultor(int row) {
        if (row >= 0) {
            Consultor c = model.getConsultor(filter.getModelRow(row));
            if (c != null) {
                if (!isSelect()) {
                    try {
                        c.setFoto(Foto.valueOf(controle.getFoto(c.getId())));
                    } catch (PersistenciaException pex) {
                        System.out.println(pex.getMessage());
                    }
                    ConsultorDialog dialog = new ConsultorDialog(this.menu, "TPB - Consultor", true);
                    dialog.setConsultor(c);
                    dialog.setNovoConsultor(false);
                    dialog.setVisible(true);
                } else {
                    setConsultor(c);
                    dispose();
                }
            }
        }
    }

    private void buscaConsultor(String texto) {
        if ((texto == null) || (texto.isEmpty())) {
            refresh(new ArrayList<Consultor>());
        } else {
            try {
                if (radio1.isSelected()) {
                    refresh(controle.pesquisar(texto));
                } else if (radio2.isSelected()) {
                    try {
                        long id = Long.parseLong(texto);
                        refresh(controle.pesquisar(id));
                    } catch (NumberFormatException nfe) {
                        refresh(new ArrayList<Consultor>());
                    }
                }
            } catch (PersistenciaException pex) {
                System.out.println(pex.getMessage());
            }
        }
    }
}
